package com.tang.subject.domain.config;

import com.tang.subject.common.consts.ThreadNameConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
@Configuration
public class ThreadPoolConfig {

    /**
     * 标签查询线程池
     *
     * @return java.util.concurrent.ThreadPoolExecutor
     * @author Tang
     * @date 2024/2/19 21:05
     **/
    @Bean(ThreadNameConst.LABEL_THREAD_POOL)
    public ThreadPoolTaskExecutor labelThreadPool() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //设置线程池优雅停机
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //设置线程池销毁时，优雅停机的等待时间
        executor.setAwaitTerminationSeconds(10);
        executor.setCorePoolSize(20);
        executor.setKeepAliveSeconds(5);
        executor.setMaxPoolSize(100);
        executor.setQueueCapacity(40);
        executor.setThreadNamePrefix("labelThreadPool-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());//满了调用线程执行，认为重要任务
        executor.setThreadFactory(new CustomNameThreadFactory(ThreadNameConst.ES_THREAD_NAME));
        executor.initialize();
        return executor;
    }

    /**
     * Es异步线程池
     *
     * @author Tang
     * @date 2024/2/24 13:05
     **/
    @Bean(ThreadNameConst.ES_THREAD_POLL)
    public ThreadPoolTaskExecutor esThreadPool() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //设置线程池优雅停机
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //设置线程池销毁时，优雅停机的等待时间
        executor.setAwaitTerminationSeconds(10);
        executor.setCorePoolSize(5);
        executor.setKeepAliveSeconds(5);
        executor.setMaxPoolSize(5);
        executor.setQueueCapacity(10);
        executor.setThreadNamePrefix("labelThreadPool-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());//满了调用线程执行，认为重要任务
        executor.setThreadFactory(new CustomNameThreadFactory(ThreadNameConst.ES_THREAD_NAME));
        executor.initialize();
        return executor;
    }
}
